package agh.sr.lab4.certsigner;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import SR.CertSignerPrx;
import SR.CertSignerPrxHelper;
import SR.DataTooLong;
import SR.IncorrectCSRFile;

public class MyCertSigner {
	public static void main(String[] args) throws DataTooLong,
			IncorrectCSRFile, IOException {

		String certServererPath = "certsigner2013:tcp -h 149.156.97.155 -p 2002";
		Ice.Communicator ic = Ice.Util.initialize(args);
		Ice.ObjectPrx base = ic.stringToProxy(certServererPath);

		CertSignerPrx certSignerPrx = CertSignerPrxHelper.checkedCast(base);
		if (certSignerPrx == null)
			throw new Error("Invalid proxy");

		System.out.println("Received cert proxy");

		String name = "Tomasz";
		String surname = "Dziok";
		String path = "certs" + File.separator;
		// String csrFileName = path + "certsbankclient.csr";
		// String certFileName = path + "bankclient.crt";
		// String csrFileName = path + "chatclient.csr";
		// String certFileName = path + "chatclient.crt";
		String csrFileName = path + "commonServer.csr";
		String certFileName = path + "commonServer.crt";

		System.out.println("Reading .csr file: " + csrFileName);
		byte[] csrFile = readFileToBytes(csrFileName);
		System.out.println("Invoking sign() service");
		byte[] response = certSignerPrx.signCSR(name, surname, csrFile);
		System.out.println("received bytes:  " + response.length);
		System.out.println("Writing response to crt file: " + certFileName);
		writeBytesToFile(certFileName, response);
		System.out.println("DONE");

		if (ic != null) {
			try {
				ic.destroy();
			} catch (Exception e) {
				System.err.println(e.getMessage());
			}
		}
		System.exit(0);
	}

	private static byte[] readFileToBytes(String csrFileName)
			throws IOException {
		FileInputStream in = (new FileInputStream(new File(csrFileName)));
		ByteArrayOutputStream ous = new ByteArrayOutputStream();

		int tmp;
		while ((tmp = in.read()) != -1) {
			ous.write(tmp);
		}

		try {
			if (ous != null)
				ous.flush();
			ous.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			if (in != null)
				in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return ous.toByteArray();
	}

	private static void writeBytesToFile(String certFileName, byte[] response)
			throws FileNotFoundException {
		FileOutputStream os = new FileOutputStream(new File(certFileName));
		try {
			os.write(response);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				os.flush();
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
